package com.ley.springboot.seed.utils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Type;
import java.util.List;

/**
 * google json utils
 **/
public class JsonUtils {

    private static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";

    private static String dateFormat;

    public JsonUtils(String dateFormat) {
        JsonUtils.dateFormat = dateFormat;
    }

    /**
     * get google json
     *
     * @see Gson
     **/
    public static Gson getGson() {
        if (StringUtils.isNotBlank(dateFormat)) {
            JsonUtils.dateFormat = DEFAULT_DATE_FORMAT;
        }
        return (new GsonBuilder()).serializeNulls().setDateFormat(JsonUtils.dateFormat).create();
    }

    /**
     * object to json
     **/
    public static String toJson(Object obj) {
        return getGson().toJson(obj);
    }

    /**
     * json to type
     *
     * @see Gson#toJson(Object, Type)
     **/
    public static String toJson(Object obj, Type type) {
        return getGson().toJson(obj, type);
    }

    /**
     * generic t to json
     **/
    public static <T> String t2Json(T t) {
        return getGson().toJson(t);
    }

    /**
     * json to generic t
     **/
    public static <T> T json2T(String jsonString, Class<T> clazz) {
        return getGson().fromJson(jsonString, clazz);
    }

    /**
     * json to collection
     **/
    public static <T> List<T> json2Collection(String jsonStr, Type type) {
        return (List<T>) getGson().fromJson(jsonStr, type);
    }

    /**
     * json to type
     *
     * @see Gson#fromJson(String, Type)
     **/
    public static <T> T fromJson(String jsonStr, Type type) {
        return getGson().fromJson(jsonStr, type);
    }

    /**
     * json to class type
     **/
    public static <T> T fromJson(String jsonStr, Class<T> clazz) {
        return getGson().fromJson(jsonStr, clazz);
    }
}
